package ldh.im.base.handler.service;

import io.netty.channel.Channel;
import ldh.im.ImConfig;
import ldh.im.base.ImSession;
import ldh.im.base.SessionManager;
import ldh.im.dto.DtoData;
import ldh.im.dto.base.ErrorResp;
import ldh.im.dto.base.Req;
import ldh.im.dto.codec.CodecFactory;
import ldh.im.dto.enmus.HandleType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池异步处理
 */
public class ThreadHandlerService extends BaseHandlerService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadHandlerService.class);

    private int threadNum = 3;
    private Map<Integer, ExecutorService> executorMap = new HashMap<>();

    public ThreadHandlerService(int threadNum) {
        this.threadNum = threadNum;
        buildExecutors();
    }

    @Override
    public void handle(Channel channel, DtoData dtoData) {
        ImSession imSession = SessionManager.getInstance().getImSession(channel);
        int userHashCode = (int) imSession.get(ImConfig.USER_HASHCODE);
        int mod = createMod(userHashCode, threadNum);
        executorMap.get(mod).execute(()->{
            try {
                LOGGER.info("线程正在处理{}用户{}的数据{}", userHashCode, imSession.get(ImConfig.USER_ID), dtoData.getCoder());
                doHandle(channel, dtoData);
            } catch (Exception e) {
                channel.writeAndFlush(new ErrorResp(500, "业务处理失败"));
                LOGGER.error("业务处理失败", e);
            }
        });
    }

    protected int createMod(int userHashCode, int threadNum) {
        return (int)userHashCode % threadNum;
    }

    private void buildExecutors() {
        for(int i=0; i<threadNum; i++) {
            executorMap.put(i, Executors.newSingleThreadExecutor());
        }
    }
}
